// Copyright (c) 2008 Matthew Johnson
// Licensed under the MIT License (see license.txt)
package actionml.interaction {
	import actionml.Global;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.text.TextField;
	
	public class ValidationInteractions {
		public static function initialize() {
			Global.initializeExtension(ValidationInteractions, DisplayObject);
		}
		public static var instanceMethods:Object = {
			requireValues: function() {
				var dependencies:Array = [];
				for each (var s:String in this.require.split(/\s*,\s*/)) {
					var d:DisplayObject = this.getValueForKeypath(s);
					dependencies.push(d);
					if (d is TextField) {
						d.addEventListener(Event.CHANGE, validate);
						continue;
					} 
					if (d.isA("ScrollableText")) {
						d.text.addEventListener(Event.CHANGE, validate);
						continue;
					} 
					if (d.isA("RadioGroup")) {
						this.root.addEventListener(d.name + "Changed", validate);
						continue;
					} 
					if (d.isA("CheckboxGroup")) {
						this.root.addEventListener(d.name + "Changed", validate);
						continue;
					}
				}
				var o:DisplayObject = this;
				function validate() {
					outer: for each (var d:Object in dependencies) {
						if (d is TextField) {
							if (d.text.length == 0) {
								o.disable();
								return;
							} else { 
								continue; 
							}
						} 
						if (d.isA("ScrollableText")) {
							if (d.text.text.length == 0) {
								o.disable();
								return;
							} else {
								continue;
							}
						} 
						if (d.isA("RadioGroup")) {
							if (d.selected == null) {
								o.disable();
								return;
							} else {
								continue;
							}
						} 
						if (d.isA("CheckboxGroup")) {
							var checked:Boolean = false;
							for each (var c:Object in d.buttons) {
								if (c.getChecked()) {
									checked = true;
									break;
								}
							}
							if (checked) {
								continue;
							} else {
								o.disable();
								return;
							}
						}
					}
					o.enable();
				}
				validate();
			}
		}
	}
}